#!/bin/sh
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

[ "$CCI_SRC" ] || export CCI_SRC=$(git rev-parse --show-toplevel)

. $CCI_SRC/lib/log.sh

check_server_ip()
{
	mkdir -p /etc/compass-ci
	cp -a $CCI_SRC/sparrow/setup.yaml /etc/compass-ci/setup.yaml
	[ -z "$server_ip" ] && . 0-package/read-config
	[ -z "$server_ip" ] && {
		log_error "ENV \$server_ip doesn't exist, please config $CCI_SRC/sparrow/setup.yaml"
		exit 1
	}
}

install_env()
{
	cd $CCI_SRC/sparrow || return
	check_server_ip
	0-package/install
	1-storage/tiny
	5-build/ipxe &
	1-storage/permission
	2-network/br0
	2-network/br1
	2-network/iptables
	3-code/git
	3-code/dev-env
	7-systemd/iBMA-install
	. /etc/profile.d/compass.sh
}

boot_ipxe()
{
	SCHED_HOST=$server_ip
	sed -i "s%172.17.0.1%${SCHED_HOST}%g" /tftpboot/boot.ipxe
	sed -i "s%3000%${SCHED_PORT:-3000}%g" /tftpboot/boot.ipxe
}

run_service()
{
        (
                cd $CCI_SRC/container/dnsmasq || return
                wget -O dnsmasq:alpine.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/dnsmasq:alpine.tar
                docker load -i dnsmasq:alpine.tar
                #./build
                echo "start dnsmasq ~~~~~~~~~~~~~~~~~~~~"
                ./start
                boot_ipxe
        )&
        (
                cd $CCI_SRC/container/qemu-efi || return
                wget -O debian:qemu-efi.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/debian:qemu-efi.tar
                docker load -i debian:qemu-efi.tar
                #./buildi
                echo "install qemu-efi~~~~~~~~"
                ./install
        )&
        (
                cd $CCI_SRC/container/fluentd-base || return
                #./build
                wget -O fluentd-base:alpine.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/fluentd-base:alpine.tar
                docker load -i fluentd-base:alpine.tar

                cd $CCI_SRC/container/sub-fluentd || return
                wget -O sub-fluentd:alpine.tar https://repo.oepkgs.net/openEuler/compass-ci/cci-deps/docker/$(arch)/sub-fluentd:alpine.tar
                docker load -i sub-fluentd:alpine.tar
                #./build
                echo "start sub-fluentd ~~~~~~~~"
                ./start
        )&
}

check_service()
{
	for service in dnsmasq sub-fluentd
	do
		docker ps | grep -q $service || {
			log_error "failed to start container $service"
			exit 1
		}
	done

	docker images | grep -q qemu-efi || {
		log_error "failed to build container qemu-efi"
		exit 1
	}
}

check_cmd()
{
	[ -n "$(command -v lockfile-create)" ] || {
		log_error "command not found: lockfile-create"
		exit 1
	}
}

main()
{
	install_env
	run_service
	wait
	check_service
	check_cmd
}

main
